package client.network;

import java.awt.Point;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import packages.Packages;

public class ClientIncomingNetwork extends Thread {

	private MessageMailBox messageMailBox;
	private InputStream istream;
	private DrawMailBox drawMailBox;

	public ClientIncomingNetwork(InputStream istream,
			MessageMailBox messageMailBox, DrawMailBox drawMailBox) {
		this.messageMailBox = messageMailBox;
		this.drawMailBox = drawMailBox;
		this.istream = istream;
	}

	@Override
	public void run() {
		while (true) {
			try {
				byte packageType = (byte) istream.read();
				String message;
				switch (packageType) {
				case Packages.PACKAGE_CHAT_MESSAGE:
					message = readMessage(istream);
					messageMailBox.addIncommingMessage(message);
					break;
				case Packages.PACKAGE_POSITIONS:
					message = readMessage(istream);
					ArrayList<Point> points = parsePositions(message);
					drawMailBox.addIncomingPoints(points);
					break;
				case Packages.PACKAGE_ROUND_OVER:
					message = readMessage(istream);
					String[] parts = message.split(",");
					messageMailBox.endGame(parts);
					break;
				case Packages.PACKAGE_WORD_TO_DRAWER:
					message = readMessage(istream);
					// ordet till ritaren
					messageMailBox.drawersWord(message);
					break;
				case Packages.PACKAGE_NAME_OF_DRAWER:
					message = readMessage(istream);
					// vem som ritar
					break;
				case Packages.PACKAGE_LENGHT_OF_WORD:
					message = readMessage(istream);
					// längden till alla utom ritaren
					messageMailBox.lengthOfWord(message);
					break;
				case Packages.PACKAGE_NEW_GAME:
					// enable gui hos clients
					messageMailBox.startGame();
					break;
				case Packages.PACKAGE_CLIENT_LIST:
					message = readMessage(istream);
					messageMailBox.updateClientList(message);
					break;
				case Packages.PACKAGE_CLEAR:
					messageMailBox.clearCanvas();
					break;
				case 0:
					break;
				case -1: // Server disconnects
					messageMailBox.serverDisconnects();
					break;
				default:
					break;
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				break;
			}

		}

	}

	private String readMessage(InputStream is) throws IOException {
		byte[] buffer = new byte[2048];
		int offset = 0;
		is.read(buffer, offset, 1);
		while (buffer[offset] != '\n') {
			offset++;
			is.read(buffer, offset, 1);
		}
		return new String(buffer, 0, offset, "UTF-8");

	}

	public ArrayList<Point> parsePositions(String mess) {
		ArrayList<Point> points = new ArrayList<Point>();
		// Format: 1 xxx,yyy xxx,yyy xxx,yyy \n//Avsluta med ETT extra space

		String[] lines = mess.trim().split(" ");
		String[] pos;
		for (int i = 0; i < lines.length; i++) {
			System.out.println(lines[i]);
			pos = lines[i].split(",");
			int x = Integer.parseInt(pos[0]);
			int y = Integer.parseInt(pos[1]);
			points.add(new Point(x, y));
		}
		return points;
	}

}
